package com.yskj.mwk.utils;
import java.security.MessageDigest;
import java.util.Base64;

public class SecurityUtils {

    // 主方法：生成最终的安全令牌
    public static String generateSecurityToken(String clientId, String plainPassword, String privateKey) throws Exception {
        // Step 1: 生成密文（MD5(明文密码 + salt)）
        String cipherText = md5(plainPassword + "jadada236t2");
        System.out.println(cipherText);
        //String cipherText="7bb9ceb6e5db406a9085a8685f3fb05d";
        // Step 2: 拼接 clientId + cipherText + privateKey
        String combinedString = clientId + cipherText + privateKey;

        // Step 3: 生成MD5哈希
        byte[] md5Bytes = md5Bytes(combinedString);

        // Step 4: Base64编码
        return Base64.getEncoder().encodeToString(md5Bytes);
    }

    // 生成MD5十六进制字符串
    private static String md5(String input) throws Exception {
        byte[] md5Bytes = md5Bytes(input);
        return bytesToHex(md5Bytes); // 返回大写字符串
    }

    // 生成MD5字节数组
    private static byte[] md5Bytes(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return md.digest(input.getBytes("UTF-8"));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = String.format("%02X", b & 0xFF); // 大写转换关键代码
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 生成MD5十六进制字符串
    private static String md52(String input) throws Exception {
        byte[] md5Bytes = md5Bytes(input);
        return bytesToHex2(md5Bytes); // 返回大写字符串
    }
    // 字节数组转十六进制字符串
    private static String bytesToHex2(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = String.format("%02x", b & 0xFF);
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 测试验证
    public static void main(String[] args) throws Exception {
        // 测试数据
        String clientId = "J0086474299";
        String password = "H5CD3zE6";
        String privateKey = "0258d71b55fc45e3ad7a7f38bf4b201a";

        // 生成令牌
        String token = generateSecurityToken(clientId, password, privateKey);
        System.out.println("Security Token: " + token);

        /* 验证步骤（可用在线工具验证）：
           1. 计算密文 MD5("myp@ssw0rdjadada236t2")
              结果：c7f2d6a5f3e4a1b9d8e7c0f5a6b3d2e1
           2. 拼接字符串 "C10001c7f2d6a5f3e4a1b9d8e7c0f5a6b3d2e1secKey_abc123"
           3. 计算MD5得到字节数组
           4. Base64编码结果
        */
    }
}